package cn.tohsaka.factory.dockercraft.Handlers;

import cn.tohsaka.factory.dockerclient.beans.Container;
import cn.tohsaka.factory.dockerclient.beans.DockerResponse;
import cn.tohsaka.factory.dockerclient.beans.details.ContainerDetails;
import cn.tohsaka.factory.dockercraft.Engines.Nodes;
import cn.tohsaka.factory.dockercraft.Engines.dockerWrapper;
import cn.tohsaka.factory.dockercraft.Interfaces.EventBasedWebSocketConnection;
import cn.tohsaka.factory.dockercraft.Libraries.EventHandler;
import cn.tohsaka.factory.dockercraft.Structs.Instance;
import cn.tohsaka.factory.dockercraft.Structs.Node;
import cn.tohsaka.factory.dockercraft.Structs.Users;
import cn.tohsaka.factory.dockercraft.Utils;
import cn.tohsaka.factory.dockercraft.kvjsonBuilder;
import cn.tohsaka.factory.eoh.interfaces.DBRequester;
import org.webbitserver.WebSocketConnection;

import java.net.URL;
import java.util.*;

/**
 * Created by Xmsoft on 2017/8/20.
 */
public class WebSocketEvents extends EventHandler {
    @Override
    public void onEvent(String e, Object data, EventBasedWebSocketConnection wsc) {
        try {
            if(e.equalsIgnoreCase("instances/list")){
                List<Instance> list = new DBRequester<Instance>(Instance.class).getAll(String.format("SELECT * FROM dc_instances WHERE uid=%s",Utils.toUid(wsc.session().get("uid"))));
                wsc.emit(e,new kvjsonBuilder().put("list",list).getJson());
            }
            if(e.equalsIgnoreCase("touch_terminal")){
                Instance inst=new DBRequester<Instance>(Instance.class).get(String.format("SELECT * FROM dc_instances WHERE uuid='%s'",data.toString().trim()));
                if(inst!=null){
                    DockerResponse<ContainerDetails> result= Nodes.get(inst.node).inspectContainerRemote(data.toString());
                    if(result.ok()){
                        String ip=result.response.getNetworkSettings().getNetworks().getBridge().getIPAddress();
                        Node node=Nodes.getNode(inst.node);
                        Long time=(new Date()).getTime();
                        String sign = Utils.getSign(ip,time,node.auth);
                        wsc.emit(e,new kvjsonBuilder().put("uuid",inst.uuid).put("url",String.format("ws://%s/ws?forward=%s&time=%d&sign=%s",new URL(node.ip).getHost()+":3001",ip,time,sign)).getJson());
                        wsc.emit(e,String.format("ws://%s/ws?forward=%s&time=%d&sign=%s","127.0.0.1:3001",ip,time,sign));
                    }
                }
            }


        }catch (Exception ev){
            ev.printStackTrace();
        }
    }
}
